﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using David.Framework.Core.Enums;
using David.WebSite.Data;

namespace David.Framework.Web.Security
{
    public class DavidFormsAuthentication
    {
        private const string AuthKey = "c9w324hh";//密钥，且必须为8位。
        private const string AuthCookieName = "David2018Auth";//cookie名称
        private const int ExpiresNumOfDay = 7;//cookie过期天数
        //private const string DomainName = "david.com";//cookie域名

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userId">用户ID</param>
        /// <param name="createPersistentCookie">是否记住登录</param>
        public static void SignIn(string userName, int userId, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("值不能为 null 或为空。", "userName");

            string cookieSaveValue = string.Format("username={0};userid={1}", userName, userId);//保存在Cookie中的值

            string cookie = EncryptionHelper.EncryptBalance(cookieSaveValue, AuthKey);

            HttpCookie authCookie = new HttpCookie(AuthCookieName, cookie);
            //authCookie.Domain = DomainName;
            authCookie.Path = "/";

            if (createPersistentCookie)
            {
                authCookie.Expires = DateTime.Now.AddDays(ExpiresNumOfDay);
            }

            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        /// <summary>
        /// 退出
        /// </summary>
        public static void SignOut()
        {
            var cookie = HttpContext.Current.Request.Cookies[AuthCookieName];

            if (cookie != null)
            {
                cookie.Value = "";
                cookie.Expires = DateTime.Now.AddDays(-1);
                //cookie.Domain = DomainName;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        public static bool IsLogin()
        {
            string value = GetCookieValue();

            if (value.Contains("username=") && value.Contains(";userid="))
            {
                return true;
            }

            return false;
        }
        /// <summary>
        /// 取到用户名
        /// </summary>
        /// <returns></returns>
        public static string GetUserName()
        {
            //string value = GetCookieValue();

            //if (value.Contains("username=") && value.Contains(";userid="))
            //{
            //    return value.Split(';')[0].Split('=')[1];
            //}
            return AdminsDataService.GetUseInfoByUserId(GetUserId()).UserName;
        }

        public static AdminRole GetUserRole()
        {
            return (AdminRole)AdminsDataService.GetUseInfoByUserId(GetUserId()).UserRole;
        }
        /// <summary>
        /// 取到用户ID
        /// </summary>
        /// <returns></returns>
        public static int GetUserId()
        {
            string value = GetCookieValue();

            if (value.Contains("username=") && value.Contains(";userid="))
            {
                int userId = 0;
                int.TryParse(value.Split(';')[1].Split('=')[1], out userId);
                return userId;
            }

            return 0;
        }

        private static string GetCookieValue()
        {
            var cookie = HttpContext.Current.Request.Cookies.Get(AuthCookieName);

            if (cookie != null)
            {
                return EncryptionHelper.DecryptBalance(cookie.Value, AuthKey);
            }

            return "";
        }

    }
}
